from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View

from apps.index.utils import get_click_list, get_user_info
from apps.news.models import News, Category
from utils import constants
from utils.response_code import RET


class IndexView(View):
    def get(self, request):
        # 1.获取点击排行数据
        click_news_list = get_click_list()
        user_info = get_user_info(request)
        # 2.获取新闻分类数据
        categories = Category.objects.all()
        # 定义列表保存分类数据
        categories_list = []

        for category in categories:
            # 拼接内容
            categories_list.append({
                "id": category.id,
                "name": category.name
            })

        context = {
            'data': {
                "user_info": user_info,
                "click_news_list": click_news_list,
                'categories_list': categories_list
            }
        }
        return render(request, 'base_index.html', context=context)


class NewsListView(View):
    """首页新闻列表"""

    def get(self, request):
        # 1. 获取参数
        page = request.GET.get("page", '1')  # 页数
        per_page = request.GET.get("per_page", constants.HOME_PAGE_MAX_NEWS)  # 每页数量
        category_id = request.GET.get("cid", '1')  # 分类id

        # 2. 校验参数
        try:
            page = int(page)
            per_page = int(per_page)
            category_id = int(category_id)
        except Exception as e:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})

        # 3. 查询数据并分页
        # 如果分类id不为1，那么添加分类id的过滤，如果等于1就是获取当前新闻就好
        if category_id != 1:
            news = News.objects.filter(category=category_id, status=0).order_by('-create_time')
        else:
            # 把filters解包传入
            news = News.objects.filter(status=0).order_by('-create_time')
        pagination = Paginator(news, per_page)
        try:
            # 获取查询出来的数据
            news_list = pagination.page(page)
            # 获取到总页数
            total_page = pagination.num_pages

            print(news_list)
            print(total_page)
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "数据查询失败"})

        news_li = []
        for news in news_list:
            news_li.append({
                "id": news.id,
                "title": news.title,
                "source": news.source,
                "digest": news.digest,
                "create_time": news.create_time,
                "index_image_url": news.index_image_url,
                "clicks": news.clicks,
            })

        # 4. 返回数据

        return http.JsonResponse(
            {'errno': RET.OK, 'errmsg': "OK", 'totalPage': total_page, 'currentPage': page, 'newsList': news_li,
             'cid': category_id})
